package freeCellDataStructures;

import java.util.ArrayList;
import java.util.List;



import freeCellBackend.Card;

public class Cascade {
	private List<OrderedCascade> cascade;
	
	public Cascade(){
		cascade = new ArrayList<OrderedCascade>();
	}
	
	public boolean add(OrderedCascade oc, boolean fromDeck){
		if(cascade.isEmpty()) {
			cascade.add(oc);
			return true;
		}
		//Checks new cascade to see if we should just add the two together
		if(cascade.get(cascade.size()-1).getTop().getValue() - 1 == oc.getBottom().getValue())
			if(cascade.get(cascade.size()-1).getTop().getSuite() % 2 != oc.getBottom().getSuite() % 2){
				cascade.get(cascade.size()-1).consolidate(oc);
				return true;
			}
		if(fromDeck)
			return cascade.add(oc);
		return false;
	}
	public OrderedCascade remove(int quantity){
		OrderedCascade oc;
		if(quantity>=cascade.get(cascade.size()-1).size()) {
			oc = cascade.remove(cascade.size()-1);
		}else if(quantity<=1) {
			oc = cascade.get(cascade.size()-1).remove(1);
		} else {
			oc = cascade.get(cascade.size()-1).remove(quantity);
		}
		return oc;
//		// index is number of cards to remove from cascade or oc.
//		//SET OC INDEX IN BOUNDS IF IT IS TOO SMALL
//		if(index < 0) {
//			index = 0;
//		}
//		//SET OC INDEX IN BOUNDS IF IT IS TOO GREAT
//		if(index > cascade.get(cascade.size()-1).size()) {
//			index = cascade.get(cascade.size()-1).size()-1;
//		}
//		//REMOVE WHOLE OC
//		if(cascade.get(cascade.size()-1).size()-1 == index) {
//			return cascade.remove(cascade.size()-1);
//		}
//		//REMOVE PART OF OC
//		if(cascade.get(cascade.size()-1).size()-1>index && index >= 0) {
//			return cascade.get(cascade.size()-1).remove(index);
//		}
//		// Never gets run.
//		return null;
	}
	
	public OrderedCascade getOrderedCascade(int index) {
		//NOT MODULARIZING CODE/ NOT OOP ENCAPSULATION
		return cascade.get(index);
	}
	public List<Card> getCascade(){
		List<Card> temp = new ArrayList<Card>();
		for(OrderedCascade oc: cascade)
			for(int i=0; i<oc.size(); i++)
				temp.add(oc.getOrderedCascadeCards(i));
		return temp;
	}
	public boolean contains(Card c) {
		for(int i=0;i<cascade.size();i++) {
			if(cascade.get(i).contains(c)) {
				return true;
			}
		}
		return false;
	}
	public int size() {
		return cascade.size();
	}
	public String toString() {
		String temp = "";
		for(OrderedCascade oc : cascade)
			temp=temp + oc.toString();
		return temp + "\n";
		
	}
}
